package utils

import (
	"alertmanagerWebhook/global"
	"bytes"
	"encoding/json"
	"io"
	"net/http"
)

func SendWebhookRequest(platform string, message interface{}, webhookURL string) error {
	data, err := json.Marshal(message)
	if err != nil {
		global.Logger.Errorf("消息JSON序列化失败: %v", err)
		return err
	}

	req, err := http.NewRequest("POST", webhookURL, bytes.NewBuffer(data))
	if err != nil {
		global.Logger.Errorf("创建HTTP请求失败: %v", err)
		return err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	global.Logger.Debugf("发送请求到%s", webhookURL)
	resp, err := client.Do(req)
	if err != nil {
		global.Logger.Errorf("HTTP请求发送失败: %v", err)
		return err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		global.Logger.Errorf("读取响应体失败: %v", err)
		return err
	}

	var response map[string]interface{}
	if err = json.Unmarshal(body, &response); err != nil {
		global.Logger.Errorf("解析响应JSON失败: %v", err)
		return err
	}

	global.Logger.Debugf("%s平台响应: %+v", platform, response)

	// 根据平台类型调用不同的错误处理
	switch platform {
	case "dingding":
		return HandleAPIError(response)
	default:
		return HandleAPIError(response)
	}
}

